# -*- coding: UTF-8 -*-
import requests
import cookielib
import execjs
import re
import json

class PSinaLogin():
    
    def __init__(self, username, pwd):
        self.username = username
        self.pwd = pwd
        self.session = requests.session()
        self.session.cookies = cookielib.LWPCookieJar()
        self.headers = {}
        self.headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
        self.headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        self.headers['Accept-Encoding'] = 'gzip, deflate, sdch'
        self.headers['Accept-Language'] = 'zh-CN,zh;q=0.8'
        self.headers['Upgrade-Insecure-Requests'] = "1"
    
    def doLogin(self):
        phantomjs = execjs.get("PhantomJS")
        with open("js/sinalogin.js", "r") as f:
            source = f.read()
        runntime = phantomjs.compile(source)
        su = runntime.call('get_name', self.username)
        post_url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)'
        prelogin_url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&' \
                        'su=' + su + '&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.18)'
        json_pattern = r'.*?\((.*)\)'
        reponse = self.session.get(prelogin_url, headers=self.headers)
        repose_str = reponse.text
        m = re.match(json_pattern, repose_str)
        pre_obj = json.loads(m.group(1))
        nonce = pre_obj['nonce']
        pubkey = pre_obj['pubkey']
        servertime = pre_obj['servertime']
        sp = runntime.call('get_pass', self.pwd, nonce, servertime, pubkey)
        data = {
            'entry': 'weibo',
            'gateway': '1',
            'from': '',
            'savestate': '7',
            'useticket': '1',
            'pagerefer': "http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl",
            'vsnf': '1',
            'su': su,
            'service': 'miniblog',
            'servertime': pre_obj['servertime'],
            'nonce': pre_obj['nonce'],
            'pwencode': 'rsa2',
            'rsakv': pre_obj['rsakv'],
            'sp': sp,
            'sr': '1366*768',
            'encoding': 'UTF-8',
            'prelt': '115',
            'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
            'returntype': 'META',
        }
        logining_page = self.session.post(post_url, data=data, headers=self.headers)
        login_loop = logining_page.content.decode("GBK")
        pa = r'location\.replace\([\'"](.*?)[\'"]\)'
        url = re.findall(pa, login_loop)[0]
        login_info = self.session.get(url)
        uid = re.findall('"uniqueid":"(\d+)",', login_info.content)[0]
        result = re.findall('"result":(true|false),', login_info.content)[0]
        if bool(result) == True:  
            url = "http://weibo.com/u/" + uid
            self.session.get(url, allow_redirects=True, headers=self.headers)
            self.session.cookies.save("cookies/logincookies", ignore_discard=True, ignore_expires=True)
            self.session.close()
        else:
            return False
